import os
import re
from pathlib import Path
import logging
from logging.handlers import TimedRotatingFileHandler
import toml
import csv
import asyncio

#
import pydash

#
from rich.logging import RichHandler

DEBUG = Path("DEBUG").exists() and Path("DEBUG").is_file()
# ================status_code================
F_SKIP = 2
F_EXIT = 1
F_OK = 0
# ================常量================
# .fill和.miss是用来填充的
SUFFIXES_VIDEO = {".mp4", ".mkv", ".avi", ".mov", ".rmvb", ".fill", ".miss"}
SENSITIVE_WORDS = {"里番", "hanime", "GHS", "ghs"}
VOLUME_MiB = 1048576
# ================logger================
logging.getLogger("httpx").setLevel(logging.ERROR)
_BACKUP_COUNT = 14

LOG_DIR = Path("logs")
LOG_DIR.mkdir(0o755, parents=False, exist_ok=True)
FILE_HANDLER = TimedRotatingFileHandler(LOG_DIR / "video.log", "midnight", backupCount=_BACKUP_COUNT, encoding="utf-8")


def redirect_logger(logger_name):
    _FILE_FORMATTER_STR = "[%(asctime)s] %(levelname)s: %(message)s"
    FILE_HANDLER.setFormatter(logging.Formatter(_FILE_FORMATTER_STR))
    result = logging.getLogger(logger_name)
    result.setLevel(logging.DEBUG if DEBUG else logging.INFO)
    result.addHandler(FILE_HANDLER)
    rich_handler = RichHandler(show_path=False, show_time=False)
    result.addHandler(rich_handler)


# ================读取设置================
def preprocess_config():
    def set_if_empty(key, value):
        if pydash.get(CONFIG, key, "") == "":
            pydash.set_(CONFIG, key, value)

    set_if_empty("metaDB.tmdb.token", os.getenv("TMDB_API_TOKEN", ""))
    set_if_empty("metaDB.bgmtv.token", os.getenv("BGMTV_API_TOKEN", ""))


CONFIG = toml.loads(Path("config.toml").read_text("utf-8"))
preprocess_config()


# ================普通函数================
TIME_FMT_STR = "%Y-%m-%d %H:%M:%S"
DATE_FMT_STR = "%Y-%m-%d"


# ========filename========
def filename_suffix(filename: str):
    return ".{}".format(filename.split(".")[-1]).lower()


def filename_stem(filename: str):
    return ".".join(filename.split(".")[:-1])


def filename_purified(text) -> str:
    text = re.sub(r"[<>\?\*/\\:\$#@&|]+|[／：]+", " ", text).strip("._ ")
    text = re.sub(r"\s+", " ", text)
    text = re.sub(r"_+", "_", text)
    text = re.sub(r"-+", "-", text)
    text = re.sub(r"\.+", ".", text)
    return text


def filename_for_search(text) -> str:
    return re.sub(r"[-_ ]+", " ", text).strip("._ ")


# ========csv========
def write_csv(file_path: Path, data):
    with open(file_path, "w", newline="", encoding="utf-8-sig") as file:
        writer = csv.writer(file)
        writer.writerows(data)


def read_csv(file_path: Path):
    with open(file_path, mode="r", encoding="utf-8-sig") as file:
        reader = csv.reader(file)
        data = [row for row in reader]
    return data
